﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Collections;
using Catering.View_Operaction;
using System.IO;
using Catering_DBOpertion;

namespace Catering.Catering_Page.Kufang
{
    public partial class Kcpd : UserIsNull
    {
        Catering.View_Operaction_Common voc = new View_Operaction_Common();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.LoadData();
            }
        }

        //加载页面数据
        public void LoadData()
        {
            //int companyid = 0;
            //if (Session["UserID"] != null)
            //{
            //    string userid = Session["UserID"].ToString();
            //    companyid = new Catering_Rules.Personnel().GetCompanyIDByPID(Convert.ToInt32(userid));
            //}
            //voc.DropDownListDataBind_Group(this.DDL_zuoyequ, companyid);
            //voc.DropDownListDataBind_Class(this.DDL_banzu, DDL_zuoyequ.SelectedValue);
            if (Session["User"] != null)
            {
                string userid = Session["PersonnelID"].ToString();
                int companyid = 0;
                int groupid = 0;
                int classid = 0;
                bool isAdmin = false;
                Bind_Data_to_Controls.GetCompanyByCurrentUser(userid, out companyid, out groupid, out classid, out isAdmin);
                if (isAdmin)
                {
                    voc.DropDownListDataBind_Group(DDL_zuoyequ, companyid);
                    voc.DropDownListDataBind_Class(DDL_banzu, DDL_zuoyequ.Items[0].Value);
                }
                else
                {
                    Bind_Data_to_Controls.Bind_Area_ddl(DDL_zuoyequ, isAdmin, groupid, companyid);
                    Bind_Data_to_Controls.Bind_Class_ddl(DDL_zuoyequ.SelectedItem, DDL_banzu, isAdmin, classid);
                }
            }

            DataTable dt_RawMaterials = new Catering_Rules.T_RawMaterials().GetAllList().Tables[0];
            this.DDL_yuanliaodalei.LoadDrop(dt_RawMaterials, "id", "TypeName", true);
            this.DDL_yuanliaodalei_SelectedIndexChanged(null, null);

            //this.Tex_chushibanzhang.Text = BingBanzhangGuanshi("厨师长");
            //this.Tex_guanshi.Text = BingBanzhangGuanshi("管事");

            DDL_banzu_SelectedIndexChanged(null, null);
            InitControlled();

            DataTable dt_kufang = new Catering_Rules.StorageRoom().GetAllList().Tables[0];
            this.DDL_kufang.LoadDrop(dt_kufang, "id", "RoomID", true);
            this.Tex_pandianriqi.Attributes.Add("onfocus", "WdatePicker({dateFmt:'yyyy-MM-dd',maxDate:'%y-#{%M+1}-%d'})");
            this.Tex_pandianriqi.Text = DateTime.Now.ToString("yyyy-MM-dd");
        }

        //选择作业区
        protected void DDL_zuoyequ_SelectedIndexChanged(object sender, EventArgs e)
        {
            voc.DropDownListDataBind_Class(DDL_banzu, DDL_zuoyequ.SelectedValue);
            InitControlled();
            DDL_banzu_SelectedIndexChanged(null, null);
        }

        protected void DDL_yuanliaodalei_SelectedIndexChanged(object sender, EventArgs e)
        {
            DataTable dt_RawMaterialsInfo = new Catering_Rules.RawMaterialsInfo().GetList("RMID=" + this.DDL_yuanliaodalei.SelectedValue).Tables[0];
            this.DDL_yuanliaoxilei.LoadDrop(dt_RawMaterialsInfo, "id", "Name", true);
        }

        //厨师班长绑定
        //private string BingBanzhangGuanshi(string strGangwei)
        //{
        //    string strName = string.Empty;
        //    Catering_Rules.ViewOperaction crvo = new Catering_Rules.ViewOperaction();
        //    string strWhere = "ClassID=" + new Catering_Rules.Personnel().GetModel(Convert.ToInt32(Session["UserID"])).ClassID + " and bName='" + strGangwei + "'";
        //    DataSet ds = crvo.GetViewToDataSet("Personnel_BranchPost", strWhere);
        //    if (ds != null && ds.Tables.Count > 0)
        //    {
        //        if (ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0)
        //        {
        //            strName = ds.Tables[0].Rows[0]["Name"] != null && ds.Tables[0].Rows[0]["Name"].ToString().Trim().Length > 1 ? ds.Tables[0].Rows[0]["Name"].ToString().Trim() : "";
        //        }
        //    }
        //    return strName;
        //}

        //盘点
        protected void BT_kaishipandian_Click(object sender, EventArgs e)
        {
            Catering.Log4NetOption.LogWirteer("aaa");
            ViewState["pandian"] = "";
            ViewState["pandian"] = this.Pandian_Database(
                this.DDL_zuoyequ.SelectedValue,
                this.DDL_banzu.SelectedValue,
                this.Tex_pandianriqi.Text,
                this.DDL_yuanliaodalei.SelectedValue,
                this.DDL_yuanliaoxilei.SelectedValue,
                this.DDL_kufang.SelectedValue);

        }

        //返回data
        public string Pandian_Database(string strGroupID, string strClassID, string strDate, string strMaxType, string strMinType, string kufang)
        {
            this.Tex_kuchunjine.Text = "";
            this.Tex_PreMonth.Text = "";
            this.Tex_NextMonth.Text = "";
            decimal dSum = 0;//库存总金额
            StringBuilder sb = new StringBuilder("");
            DateTime date = DateTime.MinValue;
            DateTime.TryParse(strDate, out date);
            DataTable dt = Pandian_Database_toDataTable(strGroupID, strClassID, date, strMaxType, strMinType, kufang);
            if (dt.Rows.Count > 0)
            {
                int i = 0;
                foreach (DataRow dr in dt.Rows)
                {
                    i += 1;
                    string css = " style='background: #E3F5FF' onmouseover=\"this.style.background='#e4f0fc'\" onmouseout=\"this.style.background='#E3F5FF'\"";
                    if (i % 2 == 1)
                    {
                        css = " style='background: #ffffff' onmouseover=\"this.style.background='#e4f0fc'\" onmouseout=\"this.style.background='#FFFFFF'\"";
                    }
                    sb.Append("<tr " + css + ">");
                    sb.Append("<td>" + i + "</td>");//dr["RAWID"]
                    sb.Append("<td>" + dr["MaterialsName"] + "</td>");
                    sb.Append("<td>" + dr["MaterialsInfoName"] + "</td>");
                    sb.Append("<td>" + dr["InDBID"] + " </td>");
                    sb.Append("<td>" + dr["MaterialName"] + " </td>");
                    sb.Append("<td>" + dr["UName"] + "</td>");
                    sb.Append("<td>" + dr["Balance"] + "</td>");
                    //sb.Append("<td>" + dr["UName"] + "</td>");
                    sb.Append("<td>" + Toolss.GetMathResult(Convert.ToDecimal(dr["Price"]), 2, 3).ToString() + "</td>");
                    sb.Append("<td>" + Toolss.GetMathResult(Convert.ToDecimal(dr["Balance"]) * Convert.ToDecimal(dr["Price"]), 2, 3).ToString() + "</td>");
                    sb.Append("<td></td>");
                    sb.Append("<td></td>");
                    sb.Append("<td></td>");
                    sb.Append("</tr>");
                    dSum += Toolss.GetMathResult(Convert.ToDecimal(dr["Balance"]) * Convert.ToDecimal(dr["Price"]), 2, 3);
                }
                dt.Dispose();
            }
            this.Tex_kuchunjine.Text = Toolss.GetMathResult(dSum, 2, 3).ToString();
            this.Tex_PreMonth.Text = Toolss.GetMathResult(new Catering_Rules.ViewOperaction().GetKuCunAmontMoneyByMonth(strGroupID, strClassID, date.AddMonths(-1), strMaxType, strMinType, kufang), 2, 3).ToString();
            this.Tex_NextMonth.Text = Toolss.GetMathResult(new Catering_Rules.ViewOperaction().GetKuCunAmontMoneyByMonth(strGroupID, strClassID, date, strMaxType, strMinType, kufang), 2, 3).ToString();
            return sb.ToString();
        }

        //根据条件获取数据
        private DataTable Pandian_Database_toDataTable(string strGroupID, string strClassID, DateTime datetime, string strMaxType, string strMinType, string kufang)
        {
            DataTable dt = new DataTable();
            string strWhere = string.Empty;
            string orderby = string.Empty;
            strWhere = "AND ClassID= " + strClassID;
            orderby = " MaterialsName,MaterialsInfoName,MaterialName ";
            if (strMaxType != "-10")
            {
                if (strMinType != "-10")
                {
                    strWhere += " and MaterialsID=" + strMaxType + " and MaterialsInfoID =" + strMinType;
                }
                else
                {
                    strWhere += " and MaterialsID=" + strMaxType;
                }
            }

            if (kufang != "-10")
            {
                strWhere += " and StorageID=" + kufang;
            }

            DataSet ds = new Catering_Rules.ViewOperaction().GetKcpd(strWhere, datetime, orderby);
            if (ds != null && ds.Tables.Count > 0)
            {
                dt = ds.Tables[0];
            }
            return dt;
        }

        //导出
        protected void BT_daochu_Click(object sender, EventArgs e)
        {
            #region old

            //Catering.View_Operaction.Caipin_Manage_Operaction cmo = new View_Operaction.Caipin_Manage_Operaction();
            //Hashtable ht = new Hashtable();
            //ht.Add("B:2", this.DDL_zuoyequ.SelectedItem.Text);
            //ht.Add("D:2", this.DDL_banzu.SelectedItem.Text);
            //ht.Add("F:2", this.DDL_kufang.SelectedItem.Text);
            //ht.Add("H:2", this.DDL_yuanliaodalei.SelectedItem.Text);
            //ht.Add("J:2", this.DDL_yuanliaoxilei.SelectedItem.Text);
            //ht.Add("B:3", this.Tex_shoukonghao.Text.Trim());
            //ht.Add("D:3", this.Tex_chushibanzhang.Text.Trim());
            //ht.Add("F:3", this.Tex_guanshi.Text.Trim());
            //ht.Add("H:3", this.Tex_pandianriqi.Text.Trim());
            //ht.Add("J:3", this.Tex_kucunshuliang.Text.Trim());
            //ht.Add("B:4", this.Tex_kuchunjine.Text.Trim());

            //DataTable dt = this.Pandian_Insert_To_Excel(
            //    this.DDL_zuoyequ.SelectedValue,
            //    this.DDL_banzu.SelectedValue,
            //    this.Tex_pandianriqi.Text,
            //    this.DDL_yuanliaodalei.SelectedValue,
            //    this.DDL_yuanliaoxilei.SelectedValue,
            //    this.DDL_kufang.SelectedValue);
            //Catering.View_Operaction.View_Operaction_Excel ex = new View_Operaction.View_Operaction_Excel();
            //ex.ExportExl("pandian", "pandian", dt, 8, 1, ht);

            #endregion

            Microsoft.Office.Interop.Excel.Application excel1 = null;
            Microsoft.Office.Interop.Excel._Worksheet ws = null;
            Microsoft.Office.Interop.Excel.Range canbie = null;
            string stick = DateTime.Now.Ticks.ToString();

            try
            {
                excel1 = new Microsoft.Office.Interop.Excel.Application();
                excel1.Application.Workbooks.Add(true);//引用Excel工作簿
                ws = new Microsoft.Office.Interop.Excel.WorksheetClass();
                ws = (Microsoft.Office.Interop.Excel._Worksheet)excel1.ActiveSheet;//获取当前活动工作薄
                //Microsoft.Office.Interop.Excel.Range canbie;//创建Range操作一行作为标题
                excel1.Visible = false;

                #region  表头

                string riqi = Tex_pandianriqi.Text;
                DateTime starttime = DateTime.MinValue;
                DateTime.TryParse(riqi, out starttime);
                string bianhao = "";//编号
                Catering_Model.ClassInfo classinfo = new Catering_Rules.ClassInfo().GetModel(Convert.ToInt32(this.DDL_banzu.SelectedValue));
                if (classinfo != null) bianhao = classinfo.temp1;
                string currentuser = "";
                if (Session["UserID"] != null)
                {
                    int personid = 0;
                    currentuser = Session["UserID"].ToString();
                    Int32.TryParse(currentuser, out personid);
                    currentuser = "";
                    if (personid > 0)
                    {
                        Catering_Model.E_Personnel person = new Catering_Rules.T_Personnel().GetModel(personid);
                        if (person != null) currentuser = person.Name;
                    }
                }


                canbie = ws.get_Range(ws.Cells[1, 1], ws.Cells[1, 12]);
                canbie.MergeCells = true;//合并单元格
                canbie.Font.Bold = 2;
                canbie.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//居中
                ws.Cells[1, 1] = this.DDL_zuoyequ.SelectedItem.Text + this.DDL_banzu.SelectedItem.Text + this.DDL_kufang.SelectedItem.Text + "库存盘点表";


                canbie = ws.get_Range(ws.Cells[2, 1], ws.Cells[2, 12]);
                canbie.MergeCells = true;//合并单元格
                ws.Cells[2, 1] = "编号:" + bianhao + "　　单位:　　　　日期:" + riqi + "　　受控号:" + this.Tex_shoukonghao.Text;

                #endregion

                #region 第一行标题

                canbie = ws.get_Range(ws.Cells[3, 1], ws.Cells[4, 1]);
                canbie.MergeCells = true;//合并单元格
                ws.Cells[3, 1] = "序号";

                canbie = ws.get_Range(ws.Cells[3, 2], ws.Cells[4, 2]);
                canbie.MergeCells = true;//合并单元格
                ws.Cells[3, 2] = "原料大类";

                canbie = ws.get_Range(ws.Cells[3, 3], ws.Cells[4, 3]);
                canbie.MergeCells = true;//合并单元格
                ws.Cells[3, 3] = "原料细类";

                canbie = ws.get_Range(ws.Cells[3, 4], ws.Cells[4, 4]);
                canbie.MergeCells = true;//合并单元格
                ws.Cells[3, 4] = "品号";

                canbie = ws.get_Range(ws.Cells[3, 5], ws.Cells[4, 5]);
                canbie.MergeCells = true;//合并单元格
                ws.Cells[3, 5] = "品名";

                canbie = ws.get_Range(ws.Cells[3, 6], ws.Cells[4, 6]);
                canbie.MergeCells = true;//合并单元格
                ws.Cells[3, 6] = "单位";

                canbie = ws.get_Range(ws.Cells[3, 7], ws.Cells[3, 9]);
                canbie.MergeCells = true;//合并单元格
                ws.Cells[3, 7] = "实际盘存";               
                ws.Cells[4, 7] = "数量";
                ws.Cells[4, 8] = "单价";
                ws.Cells[4, 9] = "金额";
                ws.Cells[4, 10] = "合格";
                ws.Cells[4, 11] = "不合格";

                canbie = ws.get_Range(ws.Cells[3,10], ws.Cells[3,11]);
                canbie.MergeCells = true;//合并单元格
                ws.Cells[3, 10] = "产品质量状况";

                canbie = ws.get_Range(ws.Cells[3, 12], ws.Cells[4, 12]);
                canbie.MergeCells = true;//合并单元格
                ws.Cells[3, 12] = "备注";

                #endregion

                int canbiehangshu = 5;//餐别行数

                DataTable dt = Pandian_Database_toDataTable(this.DDL_zuoyequ.SelectedValue, this.DDL_banzu.SelectedValue, starttime, this.DDL_yuanliaodalei.SelectedValue, this.DDL_yuanliaoxilei.SelectedValue, this.DDL_kufang.SelectedValue);
                if (dt.Rows.Count > 0)
                {
                    int i = 0;
                    foreach (DataRow dr in dt.Rows)
                    {
                        i += 1;
                        ws.Cells[canbiehangshu, 1] = i;
                        ws.Cells[canbiehangshu, 2] = dr["MaterialsName"];
                        ws.Cells[canbiehangshu, 3] = dr["MaterialsInfoName"];
                        ws.Cells[canbiehangshu, 4] = dr["InDBID"];
                        ws.Cells[canbiehangshu, 5] = dr["MaterialName"];
                        ws.Cells[canbiehangshu, 6] = dr["UName"];
                        ws.Cells[canbiehangshu, 7] = dr["Balance"];
                        //ws.Cells[canbiehangshu, 6] = dr["UName"];
                        ws.Cells[canbiehangshu, 8] = Toolss.GetMathResult(Convert.ToDecimal(dr["Price"]), 2, 3).ToString();
                        ws.Cells[canbiehangshu, 9] = Toolss.GetMathResult(Convert.ToDecimal(dr["Balance"]) * Convert.ToDecimal(dr["Price"]), 2, 3).ToString();
                        ws.Cells[canbiehangshu, 10] = "";
                        ws.Cells[canbiehangshu, 11] = "";
                        ws.Cells[canbiehangshu, 12] = "";
                        canbiehangshu++;
                    }
                    dt.Dispose();
                }

                ws.Cells.EntireColumn.AutoFit();
                canbie = ws.get_Range(ws.Cells[2, 1], ws.Cells[canbiehangshu - 1, 12]);
                canbie.Borders.LineStyle = 1;
                canbie.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlVAlign.xlVAlignCenter;//居中

                #region 底部

                canbie = ws.get_Range(ws.Cells[canbiehangshu, 1], ws.Cells[canbiehangshu, 12]);
                canbie.MergeCells = true;//合并单元格 
                ws.Cells[canbiehangshu, 1] = "库管员：　　　　　　　　厨师班长：" + this.Tex_chushibanzhang.Text + "　　　　　管事：" + this.Tex_guanshi.Text;

                #endregion

                if (!Directory.Exists(Server.MapPath("../../xls_template"))) Directory.CreateDirectory(Server.MapPath("../../xls_template"));
                ws.SaveAs(Server.MapPath("../../xls_template") + "\\" + stick + ".xls",Microsoft.Office.Interop.Excel.XlFileFormat.xlAddIn8);
            }
            finally
            {
                if (excel1 != null)
                {
                    if (ws != null)
                    {
                        if (canbie != null)
                        {
                            System.Runtime.InteropServices.Marshal.ReleaseComObject(canbie);
                            canbie = null;

                        }
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
                        ws = null;
                    }
                    excel1.Application.Workbooks.Close();
                    excel1.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel1);
                    Toolss.KillExcel(excel1);
                    excel1 = null;
                    GC.Collect();
                }
            }

            #region 发送

            try
            {
                string path = Server.MapPath("../../xls_template") + "\\" + stick + ".xls";
                System.IO.FileInfo file = new System.IO.FileInfo(path);
                Response.Clear();
                Response.Charset = "GB2312";
                Response.ContentEncoding = System.Text.Encoding.UTF8;
                // 添加头信息，,弹出另存为窗口  
                Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
                //让浏览器头显示下载信息  
                Response.AddHeader("Content-Length", file.Length.ToString());
                // 指定返回一个不能被客户端读取的流，下载  
                Response.ContentType = "application/ms-excel";
                //把文件流下载到客户端  
                Response.WriteFile(file.FullName);
                //Toolss.DeleteFile("../../xls_template/" + stick + ".xls");
                // 停止页面的执行
                Response.End();
            }
            catch
            {

            }

            #endregion



        }

        //填充到处的dt
        public DataTable Pandian_Insert_To_Excel(string strGroupID, string strClassID, string strDate, string strMaxType, string strMinType, string kufang)
        {
            DataTable dt = new Catering_DataSet.pandianDataTable();
            DateTime date = DateTime.MinValue;
            DateTime.TryParse(strDate, out date);
            DataTable dt_pandian = this.Pandian_Database_toDataTable(strGroupID, strClassID, date, strMaxType, strMinType, kufang);
            int i = 1;
            foreach (DataRow dr in dt_pandian.Rows)
            {
                DataRow drcaigou = dt.NewRow();
                drcaigou["xuhao"] = i;
                drcaigou["leibie"] = dr["MaterialsInfoName"].ToString();
                drcaigou["mingcheng"] = dr["MaterialName"].ToString();
                drcaigou["danwei"] = dr["UName"].ToString();
                drcaigou["shuliang"] = dr["Balance"].ToString();
                drcaigou["danweis"] = dr["UName"].ToString();
                drcaigou["danjia"] = Toolss.GetMathResult(Convert.ToDecimal(dr["Price"]), 2, 3);
                drcaigou["jine"] = Toolss.GetMathResult(Convert.ToDecimal(dr["Balance"]) * Convert.ToDecimal(dr["Price"]), 2, 3);
                drcaigou["hege"] = "";
                drcaigou["buhege"] = "";
                drcaigou["beizhu"] = "";

                i++;
                dt.Rows.Add(drcaigou);
            }
            return dt;
        }

        protected void DDL_banzu_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.Tex_guanshi.Text = "";
            this.Tex_chushibanzhang.Text = "";

            string banzu = DDL_banzu.SelectedValue;
            if (!string.IsNullOrEmpty(banzu) && !banzu.Equals("-10"))
            {
                string where = " ClassID=" + banzu + " AND (pid=13 OR pid=11) ";
                this.Tex_guanshi.Text = GetPersonName(where);
                where = " ClassID=" + banzu + " AND pid=14";
                this.Tex_chushibanzhang.Text = GetPersonName(where);
            }
        }

        public string GetPersonName(string StrWhere)
        {
            DataTable dt = new Catering_Rules.T_Personnel().GetList(StrWhere).Tables[0];
            string str = "";
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string name = dt.Rows[i]["Name"].ToString();
                    str += name + ",";
                }
                dt.Dispose();
            }
            return str.TrimEnd(',');
        }

        public void InitControlled()
        {
            if (!string.IsNullOrEmpty(DDL_zuoyequ.SelectedValue) && !DDL_zuoyequ.SelectedValue.Equals("-10"))
            {
                DataTable dt = new Catering_Rules.Company().GetView_CompanyClass(DDL_zuoyequ.SelectedValue, false).Tables[0];
                if (dt != null && dt.Rows.Count > 0)
                {
                    string Controlled = dt.Rows[0]["Controlled"].ToString();
                    this.Tex_shoukonghao.Text = Controlled;
                }
            }

        }

        //同步结余
        protected void Button1_Click(object sender, EventArgs e)
        {
            #region old
            
            //string sql = " delete From Balance;DBCC CHECKIDENT (Balance,  RESEED, 0) ";
            //DbHelperSQL.ExecuteSql(sql);
            //DataTable dt1 = new DataTable();
            //dt1.Columns.Add("RAWID", typeof(int));
            //dt1.Columns.Add("InDBId", typeof(string));
            //dt1.Columns.Add("ClassID", typeof(int));
            //dt1.Columns.Add("AddDate", typeof(DateTime));
            //dt1.Columns.Add("ChangNumber", typeof(decimal));
            //dt1.Columns.Add("ChangPrice", typeof(decimal));
            //dt1.Columns.Add("ChangeID", typeof(int));
            //dt1.Columns.Add("ChangeType", typeof(int));
            //DataTable dt = new Catering_Rules.InDbInfo().GetList(" 1=1 Order by IntDate ASC ").Tables[0];
            //if (dt != null && dt.Rows.Count > 0)
            //{
            //    for (int n = 0; n < dt.Rows.Count; n++)
            //    {
            //        DataRow dr = dt1.NewRow();
            //        if (dt.Rows[n]["id"] != null && dt.Rows[n]["id"].ToString() != "")
            //        {
            //            dr["ChangeID"] = int.Parse(dt.Rows[n]["id"].ToString());
            //        }
            //        if (dt.Rows[n]["ClassID"] != null && dt.Rows[n]["ClassID"].ToString() != "")
            //        {
            //            dr["ClassID"] = int.Parse(dt.Rows[n]["ClassID"].ToString());
            //        }
            //        if (dt.Rows[n]["PiaoDate"] != null && dt.Rows[n]["PiaoDate"].ToString() != "")
            //        {
            //            dr["AddDate"] = DateTime.Parse(dt.Rows[n]["PiaoDate"].ToString());
            //        }
            //        if (dt.Rows[n]["RAWID"] != null && dt.Rows[n]["RAWID"].ToString() != "")
            //        {
            //            dr["RAWID"] = int.Parse(dt.Rows[n]["RAWID"].ToString());
            //        }
            //        if (dt.Rows[n]["Number"] != null && dt.Rows[n]["Number"].ToString() != "")
            //        {
            //            dr["ChangNumber"] = decimal.Parse(dt.Rows[n]["Number"].ToString());
            //        }

            //        if (dt.Rows[n]["Price"] != null)
            //        {
            //            dr["ChangPrice"] = decimal.Parse(dt.Rows[n]["Price"].ToString());
            //        }

            //        if (dt.Rows[n]["InDBId"] != null)
            //        {
            //            dr["InDBId"] = dt.Rows[n]["InDBId"].ToString();
            //        }
            //        dr["ChangeType"] = 0;
            //        dt1.Rows.Add(dr);
            //    }
            //    dt.Dispose();
            //}
            //dt = new Catering_Rules.FromRecords().GetList(" 1=1 Order by OutDate ASC ").Tables[0];
            //if (dt != null && dt.Rows.Count > 0)
            //{
            //    for (int n = 0; n < dt.Rows.Count; n++)
            //    {
            //        DataRow dr = dt1.NewRow();
            //        if (dt.Rows[n]["id"] != null && dt.Rows[n]["id"].ToString() != "")
            //        {
            //            dr["ChangeID"] = int.Parse(dt.Rows[n]["id"].ToString());
            //        }
            //        if (dt.Rows[n]["ClassID"] != null && dt.Rows[n]["ClassID"].ToString() != "")
            //        {
            //            dr["ClassID"] = int.Parse(dt.Rows[n]["ClassID"].ToString());
            //        }
            //        if (dt.Rows[n]["OutDate"] != null && dt.Rows[n]["OutDate"].ToString() != "")
            //        {
            //            DateTime tempdate = DateTime.Parse(dt.Rows[n]["OutDate"].ToString());
            //            if (tempdate == new DateTime(tempdate.Year, tempdate.Month, tempdate.Day))
            //            {
            //                tempdate = new DateTime(tempdate.Year, tempdate.Month, tempdate.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
            //            }
            //            dr["AddDate"] = tempdate;
            //        }
            //        if (dt.Rows[n]["RAWID"] != null && dt.Rows[n]["RAWID"].ToString() != "")
            //        {
            //            dr["RAWID"] = int.Parse(dt.Rows[n]["RAWID"].ToString());
            //        }
            //        if (dt.Rows[n]["Numbers"] != null && dt.Rows[n]["Numbers"].ToString() != "")
            //        {
            //            dr["ChangNumber"] = decimal.Parse(dt.Rows[n]["Numbers"].ToString());
            //        }
            //        dr["ChangPrice"] = 0;

            //        if (dt.Rows[n]["InDBId"] != null)
            //        {
            //            dr["InDBId"] = dt.Rows[n]["InDBId"].ToString();
            //        }
            //        dr["ChangeType"] = 1;
            //        dt1.Rows.Add(dr);
            //    }
            //    dt.Dispose();
            //}
            //DataTable temp = new DataTable();
            //DataRow[] drlist = dt1.Select("", " AddDate ASC ");
            //string result = "";
            //foreach (DataRow item in drlist)
            //{
            //    int ChangeID = int.Parse(item["ChangeID"].ToString());
            //    int ClassID = int.Parse(item["ClassID"].ToString());
            //    DateTime AddDate = DateTime.Parse(item["AddDate"].ToString());
            //    int RAWID = int.Parse(item["RAWID"].ToString());
            //    decimal ChangNumber = decimal.Parse(item["ChangNumber"].ToString());
            //    decimal ChangPrice = decimal.Parse(item["ChangPrice"].ToString());
            //    string InDBId = item["InDBId"].ToString();
            //    int ChangeType = int.Parse(item["ChangeType"].ToString());
            //    string StrWhere = " ChangeID=" + ChangeID + " AND ChangeType=" + ChangeType + "  AND InDBId=" + InDBId + " ";
            //    //要删除的数据
            //    Catering_Model.BalanceInfo model = new Catering_Rules.BalanceInfo().GetModel(StrWhere, "");
            //    if (model != null) continue;
            //    if (ChangeType == 0)
            //    {
            //        bool flag = new Catering_Rules.BalanceInfo().AddInDBInfo(RAWID, ClassID, InDBId, AddDate, ChangNumber.ToString(), ChangPrice.ToString(), ChangeID);
            //        if (!flag)
            //        {
            //            result += ChangeID + "," + ChangeType + "|";
            //        }
            //    }
            //    else
            //    {
            //        int flag = new Catering_Rules.BalanceInfo().AddFromRecords(RAWID, ClassID, InDBId, AddDate, ChangNumber.ToString(), "", ChangeID);
            //        if (flag != 3)
            //        {
            //            result += ChangeID + "," + ChangeType + "|";
            //        }
            //    }
            //}

            #endregion


            string sql = " delete From Balance where classid=30 ";
            DbHelperSQL.ExecuteSql(sql);
            DataTable dt1 = new DataTable();
            dt1.Columns.Add("RAWID", typeof(int));
            dt1.Columns.Add("InDBId", typeof(string));
            dt1.Columns.Add("ClassID", typeof(int));
            dt1.Columns.Add("AddDate", typeof(DateTime));
            dt1.Columns.Add("ChangNumber", typeof(decimal));
            dt1.Columns.Add("ChangPrice", typeof(decimal));
            dt1.Columns.Add("ChangeID", typeof(int));
            dt1.Columns.Add("ChangeType", typeof(int));
            DataTable dt = new Catering_Rules.InDbInfo().GetList(" classid=30 Order by IntDate ASC ").Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int n = 0; n < dt.Rows.Count; n++)
                {
                    DataRow dr = dt1.NewRow();
                    if (dt.Rows[n]["id"] != null && dt.Rows[n]["id"].ToString() != "")
                    {
                        dr["ChangeID"] = int.Parse(dt.Rows[n]["id"].ToString());
                    }
                    if (dt.Rows[n]["ClassID"] != null && dt.Rows[n]["ClassID"].ToString() != "")
                    {
                        dr["ClassID"] = int.Parse(dt.Rows[n]["ClassID"].ToString());
                    }
                    if (dt.Rows[n]["IntDate"] != null && dt.Rows[n]["IntDate"].ToString() != "")
                    {
                        dr["AddDate"] = DateTime.Parse(dt.Rows[n]["IntDate"].ToString()).ToString("yyyy-MM-dd")+" 9:05 ";
                    }
                    if (dt.Rows[n]["RAWID"] != null && dt.Rows[n]["RAWID"].ToString() != "")
                    {
                        dr["RAWID"] = int.Parse(dt.Rows[n]["RAWID"].ToString());
                    }
                    if (dt.Rows[n]["Number"] != null && dt.Rows[n]["Number"].ToString() != "")
                    {
                        dr["ChangNumber"] = decimal.Parse(dt.Rows[n]["Number"].ToString());
                    }

                    if (dt.Rows[n]["Price"] != null)
                    {
                        dr["ChangPrice"] = decimal.Parse(dt.Rows[n]["Price"].ToString());
                    }

                    if (dt.Rows[n]["InDBId"] != null)
                    {
                        dr["InDBId"] = dt.Rows[n]["InDBId"].ToString();
                    }
                    dr["ChangeType"] = 0;
                    dt1.Rows.Add(dr);
                }
                dt.Dispose();
            }
            dt = new Catering_Rules.FromRecords().GetList(" classid=30 Order by OutDate ASC ").Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int n = 0; n < dt.Rows.Count; n++)
                {
                    DataRow dr = dt1.NewRow();
                    if (dt.Rows[n]["id"] != null && dt.Rows[n]["id"].ToString() != "")
                    {
                        dr["ChangeID"] = int.Parse(dt.Rows[n]["id"].ToString());
                    }
                    if (dt.Rows[n]["ClassID"] != null && dt.Rows[n]["ClassID"].ToString() != "")
                    {
                        dr["ClassID"] = int.Parse(dt.Rows[n]["ClassID"].ToString());
                    }
                    if (dt.Rows[n]["OutDate"] != null && dt.Rows[n]["OutDate"].ToString() != "")
                    {
                        DateTime tempdate = DateTime.Parse(dt.Rows[n]["OutDate"].ToString());
                        if (tempdate == new DateTime(tempdate.Year, tempdate.Month, tempdate.Day))
                        {
                            tempdate = new DateTime(tempdate.Year, tempdate.Month, tempdate.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
                        }
                        dr["AddDate"] = tempdate;
                    }
                    if (dt.Rows[n]["RAWID"] != null && dt.Rows[n]["RAWID"].ToString() != "")
                    {
                        dr["RAWID"] = int.Parse(dt.Rows[n]["RAWID"].ToString());
                    }
                    if (dt.Rows[n]["Numbers"] != null && dt.Rows[n]["Numbers"].ToString() != "")
                    {
                        dr["ChangNumber"] = decimal.Parse(dt.Rows[n]["Numbers"].ToString());
                    }
                    dr["ChangPrice"] = 0;

                    if (dt.Rows[n]["InDBId"] != null)
                    {
                        dr["InDBId"] = dt.Rows[n]["InDBId"].ToString();
                    }
                    dr["ChangeType"] = 1;
                    dt1.Rows.Add(dr);
                }
                dt.Dispose();
            }
            DataTable temp = new DataTable();
            DataRow[] drlist = dt1.Select("", " AddDate ASC ");
            string result = "";
            foreach (DataRow item in drlist)
            {
                int ChangeID = int.Parse(item["ChangeID"].ToString());
                int ClassID = int.Parse(item["ClassID"].ToString());
                DateTime AddDate = DateTime.Parse(item["AddDate"].ToString());
                int RAWID = int.Parse(item["RAWID"].ToString());
                decimal ChangNumber = decimal.Parse(item["ChangNumber"].ToString());
                decimal ChangPrice = decimal.Parse(item["ChangPrice"].ToString());
                string InDBId = item["InDBId"].ToString();
                int ChangeType = int.Parse(item["ChangeType"].ToString());
                string StrWhere = " ChangeID=" + ChangeID + " AND ChangeType=" + ChangeType + "  AND InDBId=" + InDBId + " ";
                //要删除的数据
                Catering_Model.BalanceInfo model = new Catering_Rules.BalanceInfo().GetModel(StrWhere, "");
                if (model != null) continue;
                if (ChangeType == 0)
                {
                    bool flag = new Catering_Rules.BalanceInfo().AddInDBInfo(RAWID, ClassID, InDBId, AddDate, ChangNumber.ToString(), ChangPrice.ToString(), ChangeID);
                    if (!flag)
                    {
                        result += ChangeID + "," + ChangeType + "|";
                    }
                }
                else
                {
                    int flag = new Catering_Rules.BalanceInfo().AddFromRecords(RAWID, ClassID, InDBId, AddDate, ChangNumber.ToString(), "", ChangeID);
                    if (flag != 3)
                    {
                        result += ChangeID + "," + ChangeType + "|";
                    }
                }
            }
            Response.Write(result);
        }

        /// <summary>
        /// 同步入库
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Btn_IndbInfo_Click(object sender, EventArgs e)
        {
            DataTable dt = new Catering_Rules.InDbInfo().GetList(" 1=1 Order by IntDate ASC ").Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    int id = Convert.ToInt32(dt.Rows[i]["ID"]);
                    int rawid = Convert.ToInt32(dt.Rows[i]["RAWID"]);
                    decimal number = Convert.ToDecimal(dt.Rows[i]["Number"]);

                    Catering_Model.E_RawMaterial model = new Catering_Rules.T_RawMaterial().GetModel(rawid);
                    if (model != null)
                    {
                        //入库单位
                        string danwei = new Catering_Rules.Units().GetModel(Convert.ToInt32(model.temp2)).UName;
                        bool iskg = true;
                        decimal guige = 1;
                        decimal UtilKg = Toolss.GetSpecifications(rawid, danwei, out iskg);
                        guige = iskg ? 1000 : 1;
                        decimal weight = Toolss.GetMathResult(UtilKg * number, 2, 3);
                        string sql = " update InDbInfo set weight='" + weight * guige + "',SumNumber=" + weight * guige + " WHERE ID=" + id;
                        DbHelperSQL.ExecuteSql(sql);
                    }
                }
                dt.Dispose();
            }

            dt = new Catering_Rules.FromRecords().GetList(" 1=1 Order by OutDate ASC ").Tables[0];
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    int id = Convert.ToInt32(dt.Rows[i]["ID"]);
                    int rawid = Convert.ToInt32(dt.Rows[i]["RAWID"]);
                    decimal number = Convert.ToDecimal(dt.Rows[i]["Numbers"]);

                    Catering_Model.E_RawMaterial model = new Catering_Rules.T_RawMaterial().GetModel(rawid);
                    if (model != null)
                    {
                        //入库单位
                        string danwei = new Catering_Rules.Units().GetModel(Convert.ToInt32(model.temp2)).UName;
                        bool iskg = true;
                        decimal guige = 1;
                        decimal UtilKg = Toolss.GetSpecifications(rawid, danwei, out iskg);
                        guige = iskg ? 1000 : 1;
                        decimal weight = Toolss.GetMathResult(UtilKg * number, 2, 3);
                        string sql = " update FromRecords set SumNumber=" + weight * guige + " WHERE ID=" + id;
                        DbHelperSQL.ExecuteSql(sql);
                    }
                }
                dt.Dispose();
            }
            View_Operaction_Common.Show(this, "同步成功！");
        }


    }
}